import re

from django.contrib.auth.backends import ModelBackend

from apps.users.models import User


class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = self.get_user_by_account(username)
        print(user,'user')
        if user and user.check_password(password):
            return user

    @staticmethod
    def get_user_by_account(account):
        try:
            if re.match(r'1[3-9]\d{9}', account):
                user = User.objects.get(mobile=account)
            else:
                user = User.objects.get(username=account)
        except User.DoesNotExist:
            return None

        else:
            return user
